import { dialog } from 'electron'
import fs from 'fs'

import {
  quicktype,
  InputData,
  jsonInputForTargetLanguage,
  JSONSchemaInput,
  FetchingJSONSchemaStore,
  TargetLanguage,
  SerializedRenderResult
} from 'quicktype-core'

// 点击打开文件
export const openFile = function () {
  const res = dialog.showOpenDialogSync({
    title: '读取文件',
    buttonLabel: '读取',
    filters: [
      { name: 'Custom File Type', extensions: ['js'] }
    ]
  })
  if (res && res[0]) {
    return fs.readFileSync(res[0])
  }
}

// 保存文件
export const saveFile = function (value: any) {
  const res = dialog.showSaveDialogSync({
    title: '保存文件',
    buttonLabel: '保存文件',
    filters: [
      { name: 'index', extensions: ['js'] }
    ]
  })
  if (res) {
    fs.writeFileSync(res, value)
    return true
  }
  return false
}

export async function quicktypeJSON (targetLanguage: string | TargetLanguage, typeName: string, jsonString: string) {
  const jsonInput = jsonInputForTargetLanguage(targetLanguage)

  // We could add multiple samples for the same desired
  // type, or many sources for other types. Here we're
  // just making one type from one piece of sample JSON.
  await jsonInput.addSource({
    name: typeName,
    samples: [jsonString]
  })

  const inputData = new InputData()
  inputData.addInput(jsonInput)

  return await quicktype({
    inputData,
    lang: targetLanguage
  })
}

export async function quicktypeJSONSchema (targetLanguage: string, typeName: string, jsonSchemaString: any) {
  const schemaInput = new JSONSchemaInput(new FetchingJSONSchemaStore())

  // We could add multiple schemas for multiple types,
  // but here we're just making one type from JSON schema.
  await schemaInput.addSource({ name: typeName, schema: jsonSchemaString })

  const inputData = new InputData()
  inputData.addInput(schemaInput)

  return await quicktype({
    inputData,
    lang: targetLanguage
  })
}

export async function main () {
  const json = await fs.promises.readFile('E:/Cocos2D_True/exploring-the-universe/assets/data/dataTechTree.json')
  const obj = JSON.parse(json.toString('utf8'))
  const jsonB = JSON.stringify(obj)
  const result = await quicktypeJSON(
    'json-schema',
    'techTree',
    jsonB
  ) as SerializedRenderResult
  const file = result.lines.join('\n')
  await fs.promises.writeFile('E:/Cocos2D_True/exploring-the-universe/assets/data/$schema.dataTechTree.json', file, { encoding: 'utf-8' })
  return true
}
